import tkinter as tk
from tkinter import ttk, messagebox
from result_gui import ResultWellGUI

class CalculationWellGUI(ResultWellGUI):
    def __init__(self, root, calculator):
        super().__init__(root, calculator)
        
    def calculate(self):
        # 检查分段和分节总长度是否一致
        try:
            # 计算分段总长度
            segment_total = sum(float(entry[0].get()) for entry in self.segment_entries if entry[0].get())
            # 计算分节总长度
            section_total = sum(float(entry.get()) for entry in self.section_entries if entry.get())
            
            # 检查总长度是否一致（考虑浮点数精度问题）
            if not abs(segment_total - section_total) < 1e-6:
                messagebox.showerror("输入错误", 
                                    f"分段总长度({segment_total:.3f}m)与分节总长度({section_total:.3f}m)不相等，请检查并修改。")
                return
        except ValueError:
            messagebox.showerror("输入错误", "请确保所有长度输入为有效的数字。")
            return
        
        # 获取基本参数
        try:
            depth = float(self.basic_entries[0].get())
            inner_diameter = float(self.basic_entries[1].get())
            top_elevation = float(self.basic_entries[2].get())
            ground_elevation = float(self.basic_entries[3].get())
            concrete_weight = float(self.basic_entries[4].get())
            
            # 获取分段参数
            segments = []
            for i, (length_entry, thickness_entry) in enumerate(self.segment_entries):
                length = float(length_entry.get())
                thickness = float(thickness_entry.get())
                segments.append({"length": length, "thickness": thickness})
            
            # 获取分节参数
            sections = []
            for i, length_entry in enumerate(self.section_entries):
                length = float(length_entry.get())
                sections.append({"length": length})
            
            # 调用计算器进行计算
            segment_results, section_results, bottom_elevation = self.calculator.calculate(
                depth, inner_diameter, top_elevation, ground_elevation, concrete_weight,
                segments, sections
            )
            
            # 更新结果表格
            for item in self.segment_tree.get_children():
                self.segment_tree.delete(item)
            
            for result in segment_results:
                self.segment_tree.insert("", tk.END, values=result)
            
            for item in self.section_tree.get_children():
                self.section_tree.delete(item)
            
            for result in section_results:
                self.section_tree.insert("", tk.END, values=result)
            
            # 绘制结果
            self.plot_results(top_elevation, bottom_elevation, ground_elevation, segments, sections)
        except ValueError as e:
            messagebox.showerror("计算错误", f"输入参数无效: {str(e)}")
        except Exception as e:
            messagebox.showerror("计算错误", f"计算过程中出现错误: {str(e)}")
    
    def clear_data(self):
        # 清空所有输入框
        for entry in self.basic_entries:
            entry.delete(0, tk.END)
        
        for entries in self.segment_entries:
            for entry in entries:
                entry.delete(0, tk.END)
        
        for entry in self.section_entries:
            entry.delete(0, tk.END)
        
        # 清空结果表格
        for item in self.segment_tree.get_children():
            self.segment_tree.delete(item)
        
        for item in self.section_tree.get_children():
            self.section_tree.delete(item)
        
        # 清空图形
        self.ax.clear()
        self.ax.text(0.5, 0.5, "点击'计算并绘图'按钮生成标高示意图", 
                    ha='center', va='center', fontsize=12, color='gray')
        self.ax.axis('off')
        self.canvas.draw()
        
        # 恢复默认值
        self.set_default_values()